<template>
  <view class="message">
    <u-toast ref="uToast"></u-toast>
    <view class="content">
      <view>防患基础信息</view>
      <u--form labelPosition="left" :model="from" :rules="rules" labelWidth="100" ref="form1">
        <view class="card">
          <u-form-item label="隐患名称" prop="yhmc" borderBottom>
            <u--input v-model="from.yhmc" border="none" placeholder="请输入隐患名称"></u--input>
          </u-form-item>
          <u-form-item label="隐患位置" prop="dyName" borderBottom @click="show =true,showType = 88,title = '隐患位置'">
            <u--input v-model="from.dyName" border="none" placeholder="请输入隐患位置" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="预案名称" prop="dyName" borderBottom @click="show =true,showType = 99,title = '预案名称'">
            <u--input v-model="from.yamc" border="none" placeholder="选择预案名称" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>12w
          </u-form-item>
          <u-form-item label="治理类型" prop="governanceType" borderBottom
                       @click="show =true,showType = 1,title = '治理类型'">
            <u--input v-model="from.governanceType" border="none" placeholder="请选择治理类型" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="隐患类型" prop="hazardType" borderBottom
                       @click="show =true,showType = 2,title='隐患类型'">
            <u--input v-model="from.hazardType" border="none" placeholder="请选择隐患类型" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="隐患等级" prop="hazardgrade" borderBottom
                       @click="show =true,showType = 3,title='隐患等级'">
            <u--input v-model="from.hazardgrade" border="none" placeholder="请选择隐患等级" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="整改资金" prop="zgzj" borderBottom>
            <u--input v-model="from.zgzj" border="none" placeholder="请输入整改金额"></u--input>
          </u-form-item>
        </view>
        <view style="color: #838383;padding: 0 0 10px 0">隐患描述</view>
        <u--textarea v-model="from.yhms" placeholder="请输入..." height="120" confirmType="next"
                     style="margin-bottom: 15px" count :maxlength="500"></u--textarea>
        <view style="color: #838383;padding:0 0 10px 0">原因分析</view>
        <u--textarea v-model="from.yyfx" placeholder="请输入..." height="120" confirmType="next"
                     style="margin-bottom: 15px" count :maxlength="500"></u--textarea>
        <view style="color: #838383;padding:0 0 10px 0">控制措施</view>
        <u--textarea v-model="from.kzcs" placeholder="请输入..." height="120" confirmType="next"
                     style="margin-bottom: 15px" count :maxlength="500"></u--textarea>
        <view style="color: #838383;padding: 0 0 10px 0">整改人信息</view>
        <view class="card">
          <!--					<u-form-item label="责任整改人" prop="zgfzr" borderBottom @click="show =true,showType = 4,title = '整改人'">-->
          <!--						<u&#45;&#45;input v-model="from.zgfzr" border="none" placeholder="请选择整改人" disabled-->
          <!--							disabledColor="#ffffff"></u&#45;&#45;input>-->
          <!--						<u-icon slot="right" name="arrow-right"></u-icon>-->
          <!--					</u-form-item>-->
          <user-pick :label="'责任整改人'" :multiple="false" :title="'责任整改人'" :placeholder="'请选择责任整改人'"
                     v-model="from.zgfzr" :prop="'zgfzr'"></user-pick>
          <u-form-item label="隐患治理期限" prop="yhzlqxs" borderBottom
                       @click="dateTimeShow =true,showType = 7,title = '隐患治理期限'">
            <u--input v-model="from.yhzlqxs" border="none" placeholder="请选择隐患治理期限" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
        </view>
        <view style="color: #838383;padding: 0 0 10px 0">验收人信息</view>
        <view class="card">
          <user-pick :label="'验收人'" :multiple="false" :title="'验收人'" :placeholder="'请选择验收人'"
                     v-model="from.ysrxm" :prop="'ysrxm'"></user-pick>
          <u-form-item label="验收时间" prop="acceptanceDate" borderBottom
                       @click="dateTimeShow =true,showType = 6,title = '验收时间'">
            <u--input v-model="from.acceptanceDate" border="none" placeholder="请选择验收时间" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
        </view>
        <view style="color: #838383;padding: 0 0 10px 0">人物环管</view>

        <view class="card">
          <u-form-item label="人物管理分类" prop="rwglfl" borderBottom
                       @click="show =true,showType = 8,title = '人物管理分类'">
            <u--input v-model="from.rwglfl" border="none" placeholder="请选择人物管理分类" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>


          <u-form-item label="发生环节" prop="fshj" borderBottom @click="show =true,showType = 9,title = '发生环节'">
            <u--input v-model="from.fshj" border="none" placeholder="请选择发生环节" disabled
                      disabledColor="#ffffff"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
        </view>

        <view class="from_text">
          <view class="photo">隐患照片</view>
          <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
                    :maxCount="3" :previewFullImage="true"></u-upload>
        </view>
      </u--form>
      <u-button text="提交" type="primary" @click="submit"></u-button>
    </view>
    <u-picker :show="show" keyName="label" :columns="columns" :title="title" @cancel="show=false" @confirm="confirm"
              @change="changeHandler"></u-picker>
    <u-datetime-picker :minDate="newData" :show="dateTimeShow" mode="datetime" :title="title"
                       @cancel="dateTimeShow =false" @confirm="checkDateTime"></u-datetime-picker>
  </view>
</template>

<script>
import {
  getDepartmentAPI,
  startInspectionAPI,
  preliminaryPlanAPI
} from "@/api/api.js";
import {
  URL
} from '@/api/request.js'
import {
  securityRisk
} from '@/api/public.js'
import userPick from "@/pages/Components/userPick";

export default {
  components: {
    userPick,
  },
  data() {
    return {
      fileList1: [],
      title: '',
      showType: 0,
      dateTimeShow: false,
      columns: [
        []
      ],
      // columnData: [
      // 	[]
      // ],
      show: false,
      newData: new Date().getTime(),
      from: {
        governanceType: '',
        hazardType: '',
        hazardgrade: '',
        yhms: '',
        yyfx: '',
        zgfzr: '',
        acceptanceDate: '',
        yssj: '',
        yhmc: '',
        zgzj: '',
        kzcs: '',
        zllx: '',
        yhlx: '',
        yhdj: '',
        yhzlqxs: '',
        yhzlqx: '',
        rwglfl: '',
        // checkTaskId:'',
        fshj: '',
        fileList: [],
        dy: '',
        dyName: '',
      },

      rules: {}
    };
  },
  onLoad(val) {

    this.from.type = val.type
    this.from.ditals = {...JSON.parse(val.form)}

  },
  watch: {
    showType(val) {
      if (val === 1) {
        this.columns = [
          ['即查即改', '限期整改']
        ]
      } else if (val === 2) {
        this.columns = [
          ['安全', '工艺', '电气', '仪表', '消防', '总图', '设备', '其他']
        ]
      } else if (val === 3) {
        this.columns = [
          ['一般隐患', '重大隐患']
        ]
      } else if (val === 4 || val === 5) {
        getDepartmentAPI({}).then((r) => {
          let msg = r.data.map((e) => {
            return e.deptName
          })
          let leader = r.data.map((e) => {
            return [e.leader]
          })
          this.columns = [msg, [r.data[0].leader]]
          this.columnData = leader
        })
      } else if (val === 8) {
        this.columns = [
          ['人的不安全行为', '物的不安全状态', '管理上的缺陷']
        ]
      } else if (val === 9) {
        this.columns = [
          ['设计 ', '产品质量缺陷', '仓储', '项目施工', '开停车', '使用操作', '维护保养', '维修', '变更', '运输']
        ]
      } else if (val === 88) {
        securityRisk({}).then((r) => {
          let msg = r.data.map((e) => {
            return {value: e.riskEventId, label: e.riskEventName}
          })
          this.columns = [msg]
          console.log(this.columns);
        })
      }else if (val === 99){
        preliminaryPlanAPI({}).then((r)=>{
          let msg = r.data.map((e) => {
            return {value: e.id, label: e.yamc}
          })
          this.columns = [msg]
        })
      }
    }
  },

  methods: {
    submit() {
      this.from.yhzp = this.from.fileList.toString()
      console.log(this.from)
      startInspectionAPI({
        isFxyh: "1",
        checkTaskId:this.from.ditals.checkTaskId,
        ...this.from,
        // ...this.from.ditals,
      }).then((r) => {
        if (r.code === 200) {
          this.$refs.uToast.show({
            type: "success",
            message: "新增成功",
            iconUrl: "https://cdn.uviewui.com/uview/demo/toast/success.png",
          });
          setTimeout((e) => {
            uni.navigateTo({
              url: '/pages/inspection/index/index'
            })
          }, 800);
        }
      })
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: URL + '/common/upload', // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
          formData: {
            user: 'file'
          },
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          },
          success: (res) => {
            this.from.fileList.push(JSON.parse(res.data).url)
            setTimeout(() => {
              resolve(res.data.data)
            }, 1000)
          }
        });
      })
    },
    checkDateTime(e) {
      const timeFormat = uni.$u.timeFormat
      switch (this.showType) {
        case 6:
          this.from.acceptanceDate = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
          this.from.yssj = timeFormat(e.value, 'yyyymmddhhMM')
          break;
        case 7:
          this.from.yhzlqxs = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
          this.from.yhzlqx = timeFormat(e.value, 'yyyymmddhhMM')
          break;
      }
      this.dateTimeShow = false
    },
    changeHandler(e) {
      if (this.showType === 4 || this.showType === 5) {
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.uPicker
        } = e
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        if (columnIndex === 0) {
          // picker为选择器this实例，变化第二列对应的选项
          picker.setColumnValues(1, this.columnData[index])
        }
      }
    },
    confirm(e) {
      if (this.showType === 1) {
        this.from.governanceType = e.value[0]
        this.from.zllx = e.indexs[0]
      } else if (this.showType === 2) {
        this.from.hazardType = e.value[0]
        this.from.yhlx = e.indexs[0] + 1
      } else if (this.showType === 3) {
        this.from.hazardgrade = e.value[0]
        this.from.yhdj = e.indexs[0]
      } else if (this.showType === 4) {
        this.from.zgfzr = e.value[1]
      } else if (this.showType === 5) {
        this.from.ysr = e.value[1]
      } else if (this.showType === 8) {
        this.from.rwglfl = e.value[0]
      } else if (this.showType === 9) {
        this.from.fshj = e.value[0]
      } else if (this.showType === 88) {
        console.log(e.value[0])
        this.from.dyName = e.value[0].label
        this.from.dy = e.value[0].value
      }else if (this.showType === 99) {
        this.from.yamc = e.value[0].label
        this.from.ya = e.value[0].value
      }
      this.show = false
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .u-upload__button {
  margin: 15px 8px;
  background: #FFF;
}

.message {
  //height: calc(100vh - 45px);
  color: #b0b0b0;
  overflow: hidden;
  width: 100%;
  background: #F6F6F6;

  .content {
    margin: 15px 20px;

    .card {
      border-radius: 8px;
      padding: 0 10px;
      margin: 15px 0;
      background: #FFF;
    }
  }
}
</style>
